if(!Billing){ //if the BSG namespace doesn't already exist...
	var Billing= {};
}


Billing.Stories = function() {
  this.dict = $H({});
}
                                                                                                
Billing.Stories.prototype.addStory = function(id, totalEl) {
  this.dict[id] = new Billing.Story(id, totalEl);
}

Billing.Stories.prototype.get = function (key) {
  return this.dict[key];
}

Billing.Story = function (id, totalEl) {
  this.totalEl = totalEl;
  this.id = id;
  this.entries = $([]);
}

Billing.Story.prototype.addEntry = function(comment, hours, label, existingId) {
  var entry = new Billing.BillingEntry(comment, hours, label, this, existingId);
  this.entries.push(entry);
  entry.render();
  this.updateTotal();
}

Billing.Story.prototype.updateTotal = function () {
   this.totalEl.innerHTML = this.totalHours();
}

Billing.Story.prototype.renderEntries = function () {
    this.entries.each(function(entry){ entry .render() });
}

Billing.Story.prototype.totalHours = function () {
  var total = 0.0;
  this.entries.each(function (e) { total += e.hours; });
  return total;
}

Billing.Label = function(labelId, name) {
  this.id = labelId;
  this.name = name;
}



Billing.BillingEntry = function (comment, hours, label, story, id) {
  this.hours = parseFloat(hours);
  this.id = id || 0;
  if(isNaN(this.hours)) {
    hours = 0.0;
  }
  this.label = label;
  this.comment = comment;
  this.story = story;
}

Billing.BillingEntry.prototype.remove = function () {
  this.tr.hide();
  this.hours = 0.0;
  this.story.updateTotal();
}

Billing.BillingEntry.prototype.render = function() {
  var tr = $E("tr");
  tr.appendChild($E("td", this.comment));
  tr.appendChild($E("td", this.label.name));
  tr.appendChild($E("td", this.hours));
  var deleteTd = $E("td", "Delete");
  deleteTd.onclick = this.remove.bindAsEventListener(this);
  tr.appendChild(deleteTd);
  this.tr = tr;
  var billingEntryTable = $("billing_entries_" + this.story.id);
  billingEntryTable.insertBefore(tr, billingEntryTable.firstChild);
}


